import { createRouter, createWebHistory } from 'vue-router'
import Layout from '../views/system/index.vue'
import { getToken } from '@/common/auth'
import useUserStore from '@/stores/user'
import { Role_Enum } from '@/common/enum'
import useEnterpriseStore from '@/stores/enterprise'
import { initLayoutGuard, loginGuard } from './guard'
import useMenuStore from '@/stores/menu'
import * as tree from '@/common/utils/tree'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import waybill from './routes/waybill'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/:enterpriseId([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})',
      component: Layout,
      redirect: { name: 'overview' },
      children: [
        {
          path: 'information',
          name: 'enterprise.information',
          component: () => import('../views/system/information/index.vue'),
          meta: {
            title: '企业信息',
          },
        },
        {
          path: 'overview',
          name: 'overview',
          component: () => import('../views/system/overview/index.vue'),
          meta: {
            title: '企业概览',
          },
        },
        // {
        //   path: 'waybill',
        //   name: 'enterprise.waybill',
        //   component: () => import('../views/system/waybill/index.vue'),
        //   meta: {
        //     title: '货运单',
        //   },
        // },
        ...waybill,
        {
          path: 'carbill',
          name: 'enterprise.carbill',
          component: () => import('../views/system/carbill/index.vue'),
          meta: {
            title: '出车单',
          },
        },
        {
          path: ':pathMatch(.*)*',
          redirect: { name: 'error.404' },
        },
      ],
    },
    {
      path: '/create',
      name: 'create',
      component: () => import('../views/create.vue'),
      meta: {
        title: '创建企业',
        public: true,
      },
      beforeEnter: [
        loginGuard,
        async (to, from) => {
          const userStore = useUserStore()
          await userStore.getUserInfo()
          if (!userStore.checkRole([Role_Enum.enterprise_boss])) return '/error/401'
        },
      ],
    },
    {
      path: '/auth',
      name: 'auth',
      component: () => import('../views/auth/index.vue'),
      meta: {
        public: true,
      },
      redirect: '/auth/login',
      children: [
        {
          path: 'login',
          name: 'auth.login',
          component: () => import('../views/auth/login/index.vue'),
          meta: {
            auth: false,
            public: true,
          },
        },
        {
          path: 'register',
          name: 'auth.register',
          component: () => import('../views/auth/register/index.vue'),
          meta: {
            auth: false,
            public: true,
          },
        },
        {
          path: 'bind',
          name: 'auth.bind',
          component: () => import('../views/auth/bind/index.vue'),
          meta: {
            public: true,
          },
        },
        {
          path: 'role',
          name: 'auth.role',
          component: () => import('../views/auth/role/index.vue'),
          meta: {
            public: true,
          },
        },
      ],
    },
    {
      path: '/error/401',
      name: 'error.401',
      component: () => import('../views/error/401.vue'),
      meta: {
        public: true,
        auth: false,
      },
    },
    {
      path: '/error/404',
      name: 'error.404',
      component: () => import('@/views/error/404'),
      hidden: true,
      meta: {
        public: true,
        auth: false,
      },
    },
  ],
})

NProgress.configure({ showSpinner: false })
// 校验登录态
router.beforeEach(loginGuard)

router.beforeEach(initLayoutGuard)

// 校验企业 只校验/:enterpriseId的路由
router.beforeEach(async (to, from) => {
  const isPublic = to.meta.public ?? false
  const userStore = useUserStore()
  const enterpriseStore = useEnterpriseStore()
  if (!to.params.enterpriseId && !isPublic) {
    if (
      !(
        userStore.checkRole(Role_Enum.enterprise_admin) ||
        userStore.checkRole(Role_Enum.enterprise_boss)
      )
    ) {
      NProgress.done()
      return '/error/401'
    }

    if (!userStore.user?.enterpriseId) {
      NProgress.done()
      if (userStore.checkRole(Role_Enum.enterprise_admin)) return '/bind'
      if (userStore.checkRole(Role_Enum.enterprise_boss)) return '/create'
    }
    await enterpriseStore.getEnterpriseInfo(userStore.user?.enterpriseId)
    return `/${enterpriseStore.enterpriseId}`
  }
  NProgress.done()
  return true
})

router.beforeEach(async (to, from) => {
  const menuStore = useMenuStore()
  const enterpriseStore = useEnterpriseStore()
  const userStore = useUserStore()
  if (to.params.enterpriseId) {
    await enterpriseStore.getEnterpriseInfo(to.params.enterpriseId)
    if (!enterpriseStore.enterpriseId) {
      NProgress.done()
      return '/error/404'
    }
    if (userStore.user?.enterpriseId && userStore.user?.enterpriseId !== to.params.enterpriseId) {
      NProgress.done()
      return '/error/401'
    }
    NProgress.done()
    await menuStore.init()
    const menu = tree.findItem(menuStore.menuTree, 'children', (item) => item.path === to.path)
    if (menu) {
      menuStore.setActive(menu.menuId)
    }
  }
  NProgress.done()
  return true
})

export default router
